package com.renhuikeji.pro.ala.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.bumptech.glide.Glide;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.github.jdsjlzx.view.CommonHeader;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.renhuikeji.pro.ala.R;
import com.renhuikeji.pro.ala.activity.ClassifyActivity;
import com.renhuikeji.pro.ala.activity.GeneralGoodsActivity;
import com.renhuikeji.pro.ala.activity.HomeGridActivity;
import com.renhuikeji.pro.ala.activity.LoginActivity;
import com.renhuikeji.pro.ala.activity.RebateShopActivity;
import com.renhuikeji.pro.ala.activity.SignInActivity;
import com.renhuikeji.pro.ala.activity.TaoBaoSearchActivity;
import com.renhuikeji.pro.ala.adapter.HomeFragGridAdapter;
import com.renhuikeji.pro.ala.adapter.HomeRecyAdapter;
import com.renhuikeji.pro.ala.bean.BasicBean;
import com.renhuikeji.pro.ala.bean.GoodsBean;
import com.renhuikeji.pro.ala.bean.IndexGoodBean;
import com.renhuikeji.pro.ala.bean.MallListBean;
import com.renhuikeji.pro.ala.bean.MemberInfoBean;
import com.renhuikeji.pro.ala.bean.MsgBean;
import com.renhuikeji.pro.ala.config.ConfigValue;
import com.renhuikeji.pro.ala.config.Constant;
import com.renhuikeji.pro.ala.utils.AliUtils.AliUtils;
import com.renhuikeji.pro.ala.utils.CheckUtil;
import com.renhuikeji.pro.ala.utils.DealResUtil;
import com.renhuikeji.pro.ala.utils.DialogUtils;
import com.renhuikeji.pro.ala.utils.NetworkManageUtil;
import com.renhuikeji.pro.ala.utils.OkHttpUtils;
import com.renhuikeji.pro.ala.utils.SPUtils;
import com.renhuikeji.pro.ala.utils.ToastUtils;
import com.renhuikeji.pro.ala.utils.glide.GlideImageLoaderForBanner;
import com.tencent.bugly.beta.Beta;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 首页
 */

public class IndexFragment extends Fragment implements TabLayout.OnTabSelectedListener, OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.index_search_rl)
    RelativeLayout indexSearchRl;
    Unbinder unbinder;
    private View view;
    private HomeFragGridAdapter gridAdapter = null;
    private int[] images = {R.mipmap.taobao, R.mipmap.coupon, R.mipmap.snapup,
            R.mipmap.juhuasuan, R.mipmap.pinduoduo, R.mipmap.withdraw, R.mipmap.jingdong,
            R.mipmap.signin};
    private String[] text = {"淘宝返利","淘抢购", "优惠券", "聚划算", "拼多多", "申请提现", "京东返利"
            , "签到送红包"};
    private FloatingActionButton floatButton = null;
    private LRecyclerView recyclerView = null;
    private int page=1;
    private int TOTAL_COUNTER = 0;
    private static final int REQUEST_COUNT = 100;
    private static int mCurrentCounter;
    private HomeRecyAdapter recyAdapter = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private Banner banner = null;
    private GridView gridItem = null;
    private TabLayout tablayout = null;
    private LinearLayout searchView = null;
    private IndexGoodBean indexGoodBean = null;
    int pastVisiblesItems;
    private static final int HIDE_THRESHOLD = 912;
    private int scrolledDistance = 0;
    private boolean controlsVisible = true;
    private TextView tvNoNet;
    private View empty;
    private String uid;
    private List<IndexGoodBean.CatArrBean> title = new ArrayList<>();
    private String session;
    private RelativeLayout main_rel;
    private GridLayoutManager manager;
    //页面滑动距离
    private int dis = 0;
    //刷新
    private boolean isToLogin=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_index, null);
        uid = (String) SPUtils.get(getActivity(), Constant.User_Uid, "");
        session = (String) SPUtils.get(getActivity(), Constant.MSESSION, "");
        mCurrentCounter = 0;
        initViews();
        initRecycler();
        if (NetworkManageUtil.checkNetworkAvailable(getActivity())) {
            DialogUtils.showProgressDlg(getActivity(), "拼命加载中....");
            getData();
        } else {
            main_rel.setVisibility(View.GONE);
            tvNoNet.setVisibility(View.VISIBLE);
            tvNoNet.setClickable(true);
            DialogUtils.stopProgressDlg();
        }

        //bugly检查升级
        if (CheckUtil.isLogin(getActivity())) {
            Beta.checkUpgrade(false, false);
        }

        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    private void initViews() {
        main_rel = (RelativeLayout) view.findViewById(R.id.main_rel);
        tvNoNet = (TextView) view.findViewById(R.id.tv_index_no_net);
        floatButton = (FloatingActionButton) view.findViewById(R.id.floating_btn_main);
        searchView = (LinearLayout) view.findViewById(R.id.main_search_ll);

        recyclerView = (LRecyclerView) view.findViewById(R.id.main_recycler);
        empty = view.findViewById(R.id.index_empty);
        tvNoNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tablayout != null) {
                    tablayout.setVisibility(View.VISIBLE);
                }
                recyclerView.setVisibility(View.VISIBLE);
                tvNoNet.setVisibility(View.GONE);
                if (NetworkManageUtil.checkNetworkAvailable(getActivity())) {
                    DialogUtils.showProgressDlg(getActivity(), "拼命加载中....");
                    isToLogin=true;
                    getData();
                } else {
                    main_rel.setVisibility(View.GONE);
                    tvNoNet.setVisibility(View.VISIBLE);
                    DialogUtils.stopProgressDlg();
                }
            }
        });
    }

    private void initTopView() {
        //悬浮按钮
        floatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.smoothScrollToPosition(0);
                floatButton.setVisibility(View.GONE);
                setSearchBarColor(R.color.transparency_title);
                //manager.scrollToPositionWithOffset(0, 0);
                //manager.setStackFromEnd(true);
            }
        });

        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), TaoBaoSearchActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initTabView() {
        if(indexGoodBean==null){
            return;
        }
        //添加tab
        for (int i = 0; i < indexGoodBean.getCatArr().size(); i++) {
            if ("1".equals(indexGoodBean.getCatArr().get(i).getLevel())) {
                title.add(indexGoodBean.getCatArr().get(i));
                tablayout.addTab(tablayout.newTab().setText(indexGoodBean.getCatArr().get(i).getTitle()));
            }
        }
        if (null != tablayout && null != tablayout.getTabAt(0)) {
            tablayout.getTabAt(0).select();
        }
        tablayout.addOnTabSelectedListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        DialogUtils.stopProgressDlg();
        if (null != tablayout && null != tablayout.getTabAt(0)) {
            tablayout.getTabAt(0).select();
        }
    }

    private void initRecycler() {
        main_rel.setVisibility(View.VISIBLE);
        tvNoNet.setVisibility(View.GONE);
        manager = new GridLayoutManager(getActivity(),2);
        recyclerView.setLayoutManager(manager);
        recyAdapter = new HomeRecyAdapter(getActivity());
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(recyAdapter);
        recyclerView.setAdapter(mLRecyclerViewAdapter);

        //设置lrecyclerview
        final DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.line_height)
                .setColorResource(R.color.line_gray)
                .build();
        recyclerView.addItemDecoration(divider);
        recyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        recyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        recyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //添加头部
        if (NetworkManageUtil.checkNetworkAvailable(getActivity())) {
            initBanner();
        }


        //设置上拉刷新
        recyclerView.setOnRefreshListener(this);
        //设置上拉加载更多
        recyclerView.setOnLoadMoreListener(this);
        //如果滑动状态glide不加载
        recyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
            @Override
            public void onScrollUp() {

            }

            @Override
            public void onScrollDown() {

            }

            @Override
            public void onScrolled(int distanceX, int distanceY) {


            }

            @Override
            public void onScrollStateChanged(int state) {
                if (state == RecyclerView.SCROLL_STATE_SETTLING) {
                    Glide.with(getActivity()).pauseRequests();
                } else {
                    Glide.with(getActivity()).resumeRequests();
                }
            }
        });
        //设置头部加载颜色
        recyclerView.setHeaderViewColor(R.color.colorAccent, R.color.fuzhu_black, R.color.colorWhite);
        //设置底部加载颜色
        recyclerView.setFooterViewColor(R.color.colorAccent, R.color.fuzhu_black, R.color.colorWhite);
        //设置底部加载文字提示
        recyclerView.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                dis += dy;
                if (dis < 0) {
                    dis = 0;
                }
                pastVisiblesItems = manager.findFirstVisibleItemPosition();
                if ((controlsVisible && dy > 0) || (!controlsVisible && dy < 0)) {
                    scrolledDistance += dy;
                }
                if (scrolledDistance > HIDE_THRESHOLD) {
                    floatButton.setVisibility(View.VISIBLE);
                    controlsVisible = false;
                    scrolledDistance = 0;

                } else if (pastVisiblesItems == 1 && !controlsVisible && dy < 0) {
                    floatButton.setVisibility(View.GONE);
                    controlsVisible = true;
                    scrolledDistance = 0;

                }
                if (dis > indexSearchRl.getHeight()) {
                    setSearchBarColor(R.color.all_pink);
                }
                if (dy < 0 && pastVisiblesItems == 1 && dis < indexSearchRl.getHeight()) {
                    setSearchBarColor(R.color.transparency_title);
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                AliUtils.showUrl(getActivity(), recyAdapter.getDataList().get(position).getCoupon_url());
            }
        });
    }

    //创建header
    private void initBanner() {
        CommonHeader header = new CommonHeader(getActivity(), R.layout.groupon_header);
        tablayout = (TabLayout) header.findViewById(R.id.order_tablayout);
        if (NetworkManageUtil.checkNetworkAvailable(getActivity())) {
            initTabView();
        }
        banner = (Banner) header.findViewById(R.id.groupon_header_banner);
        gridItem = (GridView) header.findViewById(R.id.grid_item);
        List<String> pics = new ArrayList<>();
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
//                    AliUtils.showUrl(getActivity(), indexGoodBean.getSalesArr().get(position).getClick_url());
                }
            });
            pics.add("http://img.eeyy.com/uploadfile/2015/0617/20150617093142854.jpg");
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.setImageLoader(new GlideImageLoaderForBanner());
            banner.setImages(pics);
            banner.start();


        gridAdapter = new HomeFragGridAdapter(getActivity(), images, text);
        gridItem.setAdapter(gridAdapter);
        gridItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int poisiton, long l) {
                final int mPosition = poisiton;
                final Intent i = new Intent();
                i.setClass(getActivity(), HomeGridActivity.class);
                if (null == indexGoodBean.getMallArr()) {
                    String mallUrl = ConfigValue.GRID_DO + "&uid=" + uid;
                    new OkHttpUtils().getDatas(getActivity(), mallUrl, session, new OkHttpUtils.HttpCallBack() {
                        @Override
                        public void onSusscess(String data) {
                            MallListBean mallListBean = new Gson().fromJson(data, MallListBean.class);
                            switch (mallListBean.getResult()) {
                                case "SUCESS":
                                    if (null == mallListBean.getMallArr()) {
                                        ToastUtils.toastForShort(getActivity(), "未获取到商城链接");
                                    } else {
                                        switch (mPosition) {
                                            case 0:
                                                Intent superRebateIntent = new Intent(getActivity(), GeneralGoodsActivity.class);
                                                Bundle bundle = new Bundle();
                                                bundle.putInt("type", 2);
                                                superRebateIntent.putExtra("search", bundle);
                                                startActivity(superRebateIntent);
                                                break;
                                            case 1:
                                                Intent couponIntent = new Intent(getActivity(), GeneralGoodsActivity.class);
                                                Bundle bundle2 = new Bundle();
                                                bundle2.putInt("type", 3);
                                                couponIntent.putExtra("search", bundle2);
                                                startActivity(couponIntent);
                                                break;
                                            case 2:
                                                i.putExtra("param", "juhuasuan");
                                                i.putExtra("url", mallListBean.getMallArr().getJiu());
                                                startActivity(i);
                                                break;
                                            case 3:
                                                i.putExtra("param", "te");
                                                i.putExtra("url", mallListBean.getMallArr().getTe());
                                                startActivity(i);
                                                break;
                                            case 4:
                                                startActivity(new Intent(getActivity(), TaoBaoSearchActivity.class));
                                                break;
                                            case 5:
                                                i.putExtra("param", "jd");
                                                i.putExtra("url", mallListBean.getMallArr().getJd());
                                                startActivity(i);
                                                break;
                                            case 6:
                                                i.putExtra("param", "yhd");
                                                i.putExtra("url", mallListBean.getMallArr().getYhd());
                                                startActivity(i);
                                                break;
                                            case 7:
                                                Intent rebateShop = new Intent(getActivity(), RebateShopActivity.class);
                                                rebateShop.putExtra("mall_class_style", "mallListBean");
                                                rebateShop.putExtra("mallArr", mallListBean.getMallArr());
                                                startActivity(rebateShop);
                                                break;
                                            case 8:
                                                i.putExtra("param", "xssl");
                                                i.putExtra("url", ConfigValue.NEW_USER);
                                                startActivity(i);
                                                break;
                                            case 9:

                                                startActivity(new Intent(getActivity(), SignInActivity.class));
                                                break;
                                        }
                                    }
                                    break;
                                case "NOLOGIN":
                                    ToastUtils.toastForShort(getActivity(), mallListBean.getWorngMsg());
                                    startActivity(new Intent(getActivity(), LoginActivity.class));
                                    break;
                                case "FAIL":
                                    ToastUtils.toastForShort(getActivity(), mallListBean.getWorngMsg());
                                    break;
                            }
                        }

                        @Override
                        public void onError(String meg) {
                            super.onError(meg);
                            ToastUtils.toastForShort(getActivity(), meg);
                        }
                    });
                } else {
                    switch (poisiton) {
                        case 0:
                            Intent superRebateIntent = new Intent(getActivity(), GeneralGoodsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("type", 2);
                            superRebateIntent.putExtra("search", bundle);
                            startActivity(superRebateIntent);
                            break;
                        case 1:
                            Intent couponIntent = new Intent(getActivity(), GeneralGoodsActivity.class);
                            Bundle bundle2 = new Bundle();
                            bundle2.putInt("type", 3);
                            couponIntent.putExtra("search", bundle2);
                            startActivity(couponIntent);
                            break;
                        case 2:
                            i.putExtra("param", "juhuasuan");
                            i.putExtra("url", indexGoodBean.getMallArr().getJiu());
                            startActivity(i);
                            break;
                        case 3:
                            i.putExtra("param", "te");
                            i.putExtra("url", indexGoodBean.getMallArr().getTe());
                            startActivity(i);
                            break;
                        case 4:
                            startActivity(new Intent(getActivity(), TaoBaoSearchActivity.class));
                            break;
                        case 5:
                            i.putExtra("param", "jd");
                            i.putExtra("url", indexGoodBean.getMallArr().getJd());
                            startActivity(i);
                            break;
                        case 6:
                            i.putExtra("param", "yhd");
                            i.putExtra("url", indexGoodBean.getMallArr().getYhd());
                            startActivity(i);
                            break;
                        case 7:
                            Intent rebateShop = new Intent(getActivity(), RebateShopActivity.class);
                            rebateShop.putExtra("mall_class_style", "indexGoodBean");
                            rebateShop.putExtra("mallArr", indexGoodBean.getMallArr());
                            startActivity(rebateShop);
                            break;
                        case 8:
                            i.putExtra("param", "xssl");
                            i.putExtra("url", ConfigValue.NEW_USER);
                            startActivity(i);
                            break;
                        case 9:
//                            i.putExtra("param", "yhd");
//                            i.putExtra("url", indexGoodBean.getMallArr().getYhd());
//                            startActivity(i);
                            startActivity(new Intent(getActivity(), SignInActivity.class));
                            break;
                    }
                }
            }
        });

        mLRecyclerViewAdapter.addHeaderView(header);
    }

    //-------------------------------------创建tablayout---------------------------------
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        if (position == 0) {//这是首页
            // ToastUtils.toastForShort(getActivity(), "首页");
        } else {//跳转到其他activity
            int choosePosition = tablayout.getSelectedTabPosition();
            Intent intent = new Intent(getActivity(), ClassifyActivity.class);
            intent.putExtra("cid", title.get(choosePosition).getCid());
            intent.putExtra("type", 1);
            startActivity(intent);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    public void getData() {
        OkGo.<String>post(Constant.BASE_URL+"?g=api&m=list&a=getTaobaoGoodsList")
                .params("key_word","")
                .params("type",0)
                .params("sort",1)
                .params("1page",page)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        GoodsBean bean= DealResUtil.getInstace().dealRes(getActivity(),response,new TypeToken<BasicBean<GoodsBean>>(){}.getType());
                        if(bean==null){return;}
                            TOTAL_COUNTER=bean.getTotal();
                            recyAdapter.addAll(bean.getList());
                            mCurrentCounter=recyAdapter.getItemCount();
                            recyclerView.refreshComplete(REQUEST_COUNT);

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                          ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                    }
                });
    }

    @Override
    public void onRefresh() {
        recyAdapter.clear();
        mLRecyclerViewAdapter.notifyDataSetChanged();
        page=1;
        getData();
        dis = 0;
    }

    @Override
    public void onLoadMore() {
        if (mCurrentCounter < TOTAL_COUNTER) {
            page++;
            getData();
        } else {
            recyclerView.setNoMore(true);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        AlibcTradeSDK.destory();
        unbinder.unbind();
    }

    private void setSearchBarColor(int id) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            indexSearchRl.setBackgroundColor(getResources().getColor(id, getContext().getTheme()));
        } else {
            indexSearchRl.setBackgroundColor(getResources().getColor(id));
        }
    }
    //-------------------------------end-----------------------------------------------
}
